package webprog;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import de.fhwgt.quiz.application.Catalog;
import de.fhwgt.quiz.application.Player;
import de.fhwgt.quiz.application.Quiz;
import de.fhwgt.quiz.loader.CatalogLoader;
import de.fhwgt.quiz.loader.FilesystemLoader;
import de.fhwgt.quiz.loader.LoaderException;

/**
 * Servlet implementation class Katalog
 * @author Gennadi Heimann
 * 
 * Klasse holt die Fragekatalog aus Filesystem und schickt die Namen an Client
 */
@WebServlet("/Katalog")
public class Katalog extends HttpServlet{ 
	private static final long serialVersionUID = 1L;
	
	private Map<String, Catalog> mapCatalog;
	private FilesystemLoader filesystemLoader;
	private JSONObject catalogJson;
	private Quiz quiz;
	
	public void init(ServletConfig config) throws ServletException {
		catalogJson = new JSONObject();
		filesystemLoader = new FilesystemLoader("frageCatalog");
		quiz = Quiz.getInstance();
	}
	
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("################Spiel start################");
		System.out.println("#Servlet: #Katalog#");
		response.setContentType("text/html");
		PrintWriter writer = response.getWriter();
		try {
			mapCatalog = filesystemLoader.getCatalogs();
		} catch (LoaderException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Iterator<String> iterator = mapCatalog.keySet().iterator();
		String[] catalogStringArray = new String[mapCatalog.size()];
		int i = 0;
		while(iterator.hasNext()){
			catalogStringArray[i] = iterator.next();
			i++;
		}
		for(Integer l = 0; l < mapCatalog.size(); l++){
			String key ="cat" + l.toString();
			catalogJson.put(key, catalogStringArray[l]);
		}
		writer.println(catalogJson);
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}
}
